package com.course.web.view;

import com.course.app.biz.UserBiz;
import com.course.auth.SecurityUtils;
import com.course.domain.model.Teacher;
import com.course.web.biz.WebClassBiz;
import com.course.web.component.custom.ClassTodoGrid;
import com.course.web.model.ClassItemVM;
import com.course.web.page.TeachUI;
import com.vaadin.data.Binder;
import com.vaadin.data.converter.StringToDateConverter;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by Justin on 2017/5/30.
 */
@SpringView(name = TeacherHomeView.NAME, ui = TeachUI.class)
public class TeacherHomeView extends CustomComponent implements View {
    public static final String NAME = "";

    private final UserBiz userBiz;
    private final WebClassBiz classBiz;
    private final ClassTodoGrid todoGrid;

    @Autowired
    public TeacherHomeView(UserBiz userBiz, WebClassBiz classBiz, ClassTodoGrid todoGrid) {
        this.userBiz = userBiz;
        this.classBiz = classBiz;
        this.todoGrid = todoGrid;
    }

    @Override
    public void enter(ViewChangeListener.ViewChangeEvent event) {
        String username = SecurityUtils.getName();
        Teacher teacher = userBiz.loadTeacherByUsername(username);
        VerticalLayout root = new VerticalLayout();
        HorizontalLayout info = new HorizontalLayout();
        TextField teacherName = new TextField("Teacher:");
        TextField studentName = new TextField("Student:");
        TextField className = new TextField("NextClass:");
        TextField beginTime = new TextField("BeginTime:");
        root.addComponent(info);
        root.addComponent(todoGrid);
        info.addComponent(teacherName);
        info.addComponent(studentName);
        info.addComponent(className);
        info.addComponent(beginTime);
        setCompositionRoot(root);

        root.setMargin(false);
        info.setMargin(true);
        teacherName.setEnabled(false);
        studentName.setEnabled(false);
        className.setEnabled(false);
        beginTime.setEnabled(false);
        todoGrid.enter(teacher.getId());

        ClassItemVM item = classBiz.findNextItemByTeacher(teacher.getId());
        if (item != null) {
            Binder<ClassItemVM> binder = new Binder<>(ClassItemVM.class);
            StringToDateConverter converter = new StringToDateConverter();
            binder.forField(teacherName).bind("teacher");
            binder.forField(studentName).bind("student");
            binder.forField(className).bind("task");
            binder.forField(beginTime).withConverter(converter).bind("dateTime");
            binder.setBean(item);
        }
    }
}
